package tp.tecnicasdisenio.model.autorespondedor;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import tp.tecnicasdisenio.dao.impl.jdbc.MateriaDao;
import tp.tecnicasdisenio.model.AutoRespondedorInterface;
import tp.tecnicasdisenio.model.MailInterface;
import tp.tecnicasdisenio.model.entity.Materia;
import tp.tecnicasdisenio.util.LectorPropiedades;

public class AutoRespondedor implements AutoRespondedorInterface {

//  private static final String username = LectorPropiedades.getInstance()
//      .getPropiedad(LectorPropiedades.MAIL_ACCOUNT_USERNAME);
//  private static final String password = LectorPropiedades.getInstance()
//      .getPropiedad(LectorPropiedades.MAIL_ACCOUNT_PASSWORD);
//  private static final String smtpHost = LectorPropiedades.getInstance()
//      .getPropiedad(LectorPropiedades.MAIL_ACCOUNT_SMTP_HOST);
//  private static final String smtpPort = LectorPropiedades.getInstance()
//      .getPropiedad(LectorPropiedades.MAIL_ACCOUNT_SMTP_PORT);

  @Override
  public void responderA(MailInterface mensajeAResponder, String mensaje) {
    Materia materia = MateriaDao.getInstance().getPorEmail(mensajeAResponder.getTo().get(0));
    String email = materia.getEmail();
    String password = materia.getPassword();
    String smtpHost = materia.getSmtpHost();
    String smtpPort = materia.getSmtpPort();
    Session session = obtenerSesion(email, password, smtpHost, smtpPort);

    try {
      InputStream is = new ByteArrayInputStream(
          mensajeAResponder.getMIME().getBytes());
      MimeMessage mimeOriginal = new MimeMessage(session, is);
      reply(mimeOriginal, mensaje);
    } catch(MessagingException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void reenviarA(MailInterface mensajeAReenviar, String email) {
    Materia materia = MateriaDao.getInstance().getPorEmail(mensajeAReenviar.getTo().get(0));
    String emailMateria = materia.getEmail();
    String password = materia.getPassword();
    String smtpHost = materia.getSmtpHost();
    String smtpPort = materia.getSmtpPort();
    Session session = obtenerSesion(emailMateria, password, smtpHost, smtpPort);

    try {
      InputStream is = new ByteArrayInputStream(
          mensajeAReenviar.getMIME().getBytes());
      MimeMessage mimeOriginal = new MimeMessage(session, is);
      forward(mimeOriginal, email);
    } catch(MessagingException e) {
      e.printStackTrace();
    }
  }

  private Session obtenerSesion(final String username, final String password, final String smtpHost, final String smtpPort) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);

    Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
          }
        });
    return session;
  }

  private void reply(MimeMessage mimeOriginal, String mensaje) {
    try {
      Message reply = mimeOriginal.reply(false);
      reply.setFrom(mimeOriginal.getAllRecipients()[0]);
      reply.setReplyTo(new Address[] {mimeOriginal.getAllRecipients()[0]});
      reply.setText(mensaje + "\n\n");
      despacharEmail(reply);
    } catch(MessagingException e) {
      e.printStackTrace();
    }
  }

  private void forward(MimeMessage mimeOriginal, String destinatario) {
    try {
      MimeMessage forward = new MimeMessage(mimeOriginal);
      forward.setFrom(mimeOriginal.getAllRecipients()[0]);
      forward.setReplyTo(new Address[] {mimeOriginal.getAllRecipients()[0]});
      forward.setRecipient(RecipientType.TO, new InternetAddress(destinatario,
          true));
      despacharEmail(forward);
    } catch(AddressException e) {
      e.printStackTrace();
    } catch(MessagingException e) {
      e.printStackTrace();
    }
  }

  private void despacharEmail(Message mail) {
    try {
      Transport.send(mail);
    } catch(MessagingException e) {
      e.printStackTrace();
    }
  }
}
